import OnSaleAPI from '@/api/OnSale';
import {
  Box,
  Icon,
  mapField,
  PaginationTable,
  PopoverConfirm,
  SearchFields,
  SelectWithEmpty,
  useCall,
  usePaginationCommon,
} from '@/components';
import { CompanySelectField, LinkWithSelectCompany } from '@/pages/components';
import { forkHandler, pathJoin } from '@/utils';
import { Button, Space } from 'antd';
import React from 'react';
import { Link } from 'react-router-dom';
import styles from './sales.less';
import useOrgData from './components/useOrgData';

const FIELDS = [
  [['searchFuzzy', 'package_code'], '组合编码'],
  [['searchFuzzy', 'on_sale_name'], '在售名称'],
  [
    ['t', 'onSaleStatus'],
    '停/在售',
    SelectWithEmpty,
    {
      valueEmpty: '',
      options: [
        { label: '在售', value: '1' },
        { label: '停售', value: '2' },
      ],
    },
  ],
  [
    ['searchFuzzy', 'shelves'],
    '发布状态',
    SelectWithEmpty,
    {
      valueEmpty: '',
      options: [
        { label: '上架', value: '1' },
        { label: '下架', value: '0' },
      ],
    },
  ],
  [
    ['searchFuzzy', 'is_electric_pin'],
    '是否支持电投',
    SelectWithEmpty,
    {
      valueEmpty: '',
      options: [
        { label: '支持', value: '1' },
        { label: '不支持', value: '0' },
      ],
    },
  ],
  [
    ['searchFuzzy', 'insure_place'],
    '计划书投保地区',
    'tree',
    {
      getFieldProps() {
        return {
          treeNodeFilterProp: 'label',
          treeData: useOrgData() || [],
          allowClear: true,
        };
      },
    },
  ],
  [['t', 'companyCode'], '保险公司', CompanySelectField],
  [
    ['sectionStartParams', 'create_time'],
    '创建日期',
    'named-range',
    { endName: ['../', 'sectionEndParams', 'create_time'] },
  ],
  [
    ['sectionStartParams', 'on_sale_begin_time'],
    '销售日期',
    'named-range',
    { endName: ['../', 'sectionEndParams', 'on_sale_end_time'] },
  ],
  [['searchFuzzy', 'is_electricPin'], '', null, { hidden: true }],
].map(mapField);

const COLUMNS = [
  { dataIndex: 'packageCode', title: '组合编码', width: 140, sorter: true, ellipsis: true },
  { dataIndex: 'onSaleName', title: '名称', minWidth: 220, ellipsis: true },
  { dataIndex: 'companyName', title: '保险公司', width: 96, ellipsis: true },
  {
    dataIndex: 'saleBussessType',
    title: '业务分类',
    dict: 'agency',
    width: 64,
    ellipsis: true,
  },
  // { dataIndex: 'onSaleBeginTime', title: '开始时间', width: 110, format: 'date', sorter: true },
  // { dataIndex: 'onSaleEndTime', title: '结束时间', width: 110, format: 'date', sorter: true },
  { dataIndex: 'isElectricPin', title: '在线投保', map: { 1: '支持' }, fallback: '不支持', width: 64 },
  { dataIndex: 'shelves', title: '发布状态', map: { 1: '上架' }, fallback: '下架', width: 64 },
  {
    dataIndex: 'onSaleStatus',
    title: '售卖状态',
    map: { 1: '在售', 2: '停售' },
    fallback: ' --',
    width: 64,
  },
  { dataIndex: 'isRecommend', title: '是否推荐', map: { 1: '是' }, fallback: '否', width: 64 },
  {
    dataIndex: 'createTime',
    title: '创建日期',
    width: 110,
    format: 'date',
    sorter: true,
    defaultSortOrder: 'descend',
  },
];

const ACTIONS = {
  edit: (r) => (
    <Link to={pathJoin('addPage', { onsaleId: r.id })}>
      <Button type='link' size='small' icon={<Icon type='edit' />} />
    </Link>
  ),
  del: {
    confirm: void 0,
    text(row) {
      return (
        <Button
          type='link'
          size='small'
          disabled={row.shelves === '1'}
          title={row.shelves === '1' ? '发布的产品无法删除' : null}
          icon={<Icon type='delete' />}
        />
      );
    },
  },
  toggleShelves: (r) => (
    <Button type='link' size='small'>
      {r.shelves === '1' ? '下架' : '上架'}
    </Button>
  ),
  toggleOnSale: (r) => (
    // r.isElectricPin === '1' ? (
    //   <Button type='link' size='small'>
    //     {r.onSaleStatus === '1' ? '停售' : '在售'}
    //   </Button>
    // ) : null,
    <Button type='link' size='small'>
      {r.onSaleStatus === '1' ? '停售' : '在售'}
    </Button>
  ),
  toggleRecommend: (r) => (
    <Button type='link' size='small'>
      {r.isRecommend === '1' ? '不推荐' : '推荐'}
    </Button>
  ),
  download: (r) => (
    <Button type='link' size='small'>
      导出
    </Button>
  ),
  /*iframe: (r) => (
    <Link
      to={pathJoinParams('Iframe', {
        iframe: `/jtproduct/shtic-dist/#/main/businessManage/configView/${r.packageCode}/${r.packageCode.substr(2)}`,
      })}
    >
      <Button type='link' size='small'>
        发布
      </Button>
    </Link>
  ),*/
};

const downFileText = (file) => {
  let blob = new Blob([file], { type: 'sql/plain' });
  let url = window.URL.createObjectURL(blob);
  let a = document.createElement('a');
  a.href = url;
  a.download = new Date().getTime() + '.sql';
  a.click();
  window.URL.revokeObjectURL(url);
  a = null;
};

function InSalesPage() {
  const { tableRef, searchData, onSearch, onSelect, selectedRef, hasSelected, reset } = usePaginationCommon();

  const onBatchDel = useCall(forkHandler(() => OnSaleAPI.remove(selectedRef.current), reset, true));
  const onBatchDownload = useCall(
    forkHandler(() => {
      let packageCodes = [];
      for (let i = 0; i < selectedRef.current.length; i++) {
        packageCodes.push(tableRef.current.getData().find((item) => item.id === selectedRef.current[i]).packageCode);
      }
      OnSaleAPI.downloadFile(packageCodes)
        .then((file) => {
          downFileText(file);
        })
        .catch((file) => {
          downFileText(file);
        });
    }),
  );
  const onDel = useCall(forkHandler((row) => OnSaleAPI.remove([row.id]), reset, true));
  const onToggleOnSale = useCall(
    forkHandler(
      (row) =>
        OnSaleAPI.insertOrUpdate({
          ...row,
          onSaleStatus: row.onSaleStatus === '1' ? '2' : '1',
        }),
      reset,
      true,
    ),
  );
  const onToggleShelves = useCall(
    forkHandler(
      (row) =>
        OnSaleAPI.insertOrUpdate({
          ...row,
          shelves: row.shelves === '1' ? '0' : '1',
        }),
      reset,
      true,
    ),
  );

  const onToggleRecommend = useCall(
    forkHandler(
      (row) =>
        OnSaleAPI.insertOrUpdate({
          ...row,
          isRecommend: row.isRecommend === '1' ? '0' : '1',
        }),
      reset,
      true,
    ),
  );

  const onDownload = useCall(
    forkHandler((row) => {
      OnSaleAPI.downloadFile([row.packageCode])
        .then((file) => {
          downFileText(file);
        })
        .catch((file) => {
          downFileText(file);
        });
    }),
  );

  return (
    <>
      <SearchFields fields={FIELDS} onSubmit={onSearch} onReset={onSearch} />

      <Box flex jus='between' py={2}>
        {hasSelected && (
          <Space>
            <PopoverConfirm onOk={onBatchDel}>
              <Button>批量删除</Button>
            </PopoverConfirm>
            <PopoverConfirm onOk={onBatchDownload}>
              <Button>批量导出</Button>
            </PopoverConfirm>
          </Space>
        )}
        <span />

        <LinkWithSelectCompany to='addPage'>
          <Button>+新增</Button>
        </LinkWithSelectCompany>
      </Box>

      <PaginationTable
        ref={tableRef}
        className={styles.salesTable}
        service={OnSaleAPI.findByPage}
        serviceData={searchData}
        columns={COLUMNS}
        actions={ACTIONS}
        actionWidth={240}
        rowSelection={{ onChange: onSelect }}
        onDel={onDel}
        onToggleOnSale={onToggleOnSale}
        onToggleShelves={onToggleShelves}
        onToggleRecommend={onToggleRecommend}
        onDownload={onDownload}
        scroll={{ x: false }}
      />
    </>
  );
}

export default InSalesPage;
